package com.pdool.game.logic.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
/**
 * 排行榜逻辑处理类
 */
@Service
public class RankService {
    @Resource
    RedisTemplate<String, String> redisTemplate;

    double timeScore() {
        long updateTime = System.currentTimeMillis();
        return 1 - updateTime / Math.pow(10, (int) Math.log10(updateTime) + 1);
    }

    /**
     * 更新redis排行榜，基于sortedset,返回void
     */
    public void updateScore(long roleId, int score) {
        String roleIdStr = String.valueOf(roleId);
        double scoreD = score + timeScore();
        redisTemplate.opsForZSet().add("rank", roleIdStr, scoreD);

        Long rank = redisTemplate.opsForZSet().zCard("rank");
        if (rank >= 100) {
            redisTemplate.opsForZSet().popMin("rank");
        }
    }


    /**
     * 查询前100名的玩家
     *
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> query100() {
        Set<ZSetOperations.TypedTuple<String>> rank = redisTemplate.opsForZSet().reverseRangeWithScores("rank", 0, 100);
        return rank;
    }
}
